package com.example.tliaswebmanagement.Interceptor;

import com.example.tliaswebmanagement.util.CurrentHolder;
import com.example.tliaswebmanagement.util.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

//jwt令牌检验拦截器
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求url
        String url = request.getRequestURI();
        //2.判断是否是登录请求
        if (url.contains("login")) {
            //登录请求，放行
            log.info("登录请求，放行");
            return true;
        }
        //3.获取请求头中的令牌
        String jwt = request.getHeader("token");

        //4.判断令牌是否存在
        if (!StringUtils.hasLength(jwt)) {
            //令牌不存在，拦截
            log.info("令牌不存在，拦截");
            response.setStatus(401);
            return false;
        }
        //5. 解析token
        try{
            Map<String,Object> claims=JwtUtils.parseJwtToken(jwt);
            System.out.println(claims);
            String empid=claims.get("id").toString();

            System.out.println(empid);
            CurrentHolder.setCurrentId(empid);
            System.out.println(CurrentHolder.getCurrentId());

        }catch (Exception e){
            e.printStackTrace();
            log.info("令牌解析失败，拦截");
            response.setStatus(401);
            return false;
        }
        //6.令牌存在，放行
        log.info("{}",jwt);
        log.info("令牌存在，放行");


        return true;
    }
}
